package com.hfuu.utils;

import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;

/**
 * Author: admin
 * Date: 2018/4/25
 * time: 下午5:55
 */
public class FileUtils {

    public static String upload(@RequestParam("file") MultipartFile file, String filePath) throws IOException {
        if (!file.isEmpty()) {
            String saveFileName = file.getOriginalFilename();
            if (StringUtils.isEmpty(saveFileName)) {
                return null;
            }
            String fileName = new String(saveFileName.getBytes("UTF-8"),"iso-8859-1");
            String[] strs = fileName.split("\\.");
            String lastName = strs[0] + "_" + System.currentTimeMillis() + "." + strs[1];
            try {
                org.apache.commons.io.FileUtils.copyInputStreamToFile(file.getInputStream(),
                        new File(filePath, lastName));
            } catch (Exception e) {
                e.printStackTrace();
            }
           return lastName;
        }
        return null;
    }

    public static ResponseEntity<byte[]> downLoad(String filePath, String fileName) {
        HttpHeaders headers = new HttpHeaders();
        //为了解决中文名称乱码问题
        File fileWriter = new File(filePath);
        headers.setContentDispositionFormData("attachment", fileName);
        headers.setContentType(org.springframework.http.MediaType.APPLICATION_OCTET_STREAM);
        ResponseEntity<byte[]> result = null;
        try {
            result = new ResponseEntity<>(org.apache.commons.io.FileUtils.readFileToByteArray(fileWriter),
                    headers, HttpStatus.CREATED);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return result;
    }

    public static ResponseEntity<byte[]> downLoad1(String filePath, String fileName) {
        HttpHeaders headers = new HttpHeaders();
        //为了解决中文名称乱码问题
        File fileWriter = new File(filePath + fileName);
        headers.setContentDispositionFormData("attachment", fileName);
        headers.setContentType(org.springframework.http.MediaType.APPLICATION_OCTET_STREAM);
        ResponseEntity<byte[]> result = null;
        try {
            result = new ResponseEntity<>(org.apache.commons.io.FileUtils.readFileToByteArray(fileWriter),
                    headers, HttpStatus.CREATED);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return result;
    }
}
